from ldap3 import Server, Connection, ALL

LDAP_URL = '192.168.110.172:389'
USER = 'admin'
PASSWORD = '12345678'


class LDAP():
    def ldap_connection(self):
        total_entries = 0
        server = Server('192.168.110.172:389', get_info=ALL)
        conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=domain,dc=com', '12345678',
                          auto_bind=True)
        conn.search('ou=groups,dc=domain,dc=com', '(objectclass=person)')
        search = conn.entries
        print("\r\ngroups_data\r\n", search)
        conn.search('dc=domain,dc=com', '(objectclass=person)')
        search = conn.entries
        print("\r\ndata\r\n", search)
        conn.add('ou=上海,dc=domain,dc=com', 'organizationalUnit')
        # Add a new user
        conn.add('cn=30303,ou=上海,dc=domain,dc=com', 'inetOrgPerson',
                 {'givenName': 'Beatrix', 'sn': 'Young', 'departmentNumber': 'DEV', 'telephoneNumber': 1111})
        detail = server.schema.object_classes['inetOrgPerson']
        conn.search('ou=上海,dc=domain,dc=com', '(cn=30303)',
                    attributes=['objectclass', 'sn', 'cn', 'givenname'])
        add = conn.entries[0]
        print("add\r\n", add)
        conn.modify_dn('cn=test001,ou=上海,dc=domain,dc=com', 'cn=test002')
        conn.search('ou=上海,dc=domain,dc=com', '(cn=test002)',
                    attributes=['objectclass', 'sn', 'cn', 'givenname'])
        modify = conn.entries[0]
        print("modify\r\n", modify)
        total_entries += len(conn.response)
        for entry in conn.response:
            print(entry['dn'], entry['attributes'])
        # perform a Delete operation
        message_id = conn.delete('cn=test001,ou=上海,dc=domain,dc=com')
        # perform the Abandon operation
        delete = conn.abandon(message_id)


if __name__ == "__main__":
    ldap = LDAP()
    ldap.ldap_connection()
